package com.kzw.oa.service.ext;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.service.hibernate.DefaultEntityManager;
import com.kzw.core.util.AppUtil;
import com.kzw.core.util.ContextUtil;
import com.kzw.oa.enums.RoleType;
import com.kzw.oa.model.system.AppRole;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.model.system.Department;
import com.kzw.oa.model.system.SysConfig;
import com.kzw.oa.model.system.UserOrg;
import com.kzw.oa.service.system.SysConfigService;


@Service
@Transactional
public class AppUserService2 extends DefaultEntityManager<AppUser, Long>{

	@Autowired
	private SysConfigService sysConfigService;
	
	@Transactional(readOnly=true)
	public String getCurUserInfo(){
	    AppUser currentUser = ContextUtil.getCurrentUser();
	    
	    String rolestr = ";";
	    Set<AppRole> roles = currentUser.getRoles();
	    if(roles.size()>0){
	    	for (AppRole r : roles) {
	    		rolestr += r.getRoleId()+";";
			}
	    }
	    
		Department curDep = currentUser.getDepartment();
		if (curDep == null) {// 若所属部门为空，则设置一个缺省的部门
			curDep = new Department();
			curDep.setDepId(0L);
			curDep.setDepName(AppUtil.getCompanyName());
		}
		
		//去掉公共权限
//		List<IndexDisplay> list = indexDisplayService.findByUser(currentUser.getUserId());
//		List<PanelItem> items = new ArrayList<PanelItem>();
//		for (IndexDisplay id : list) {
//			PanelItem pi = new PanelItem();
//			pi.setPanelId(id.getPortalId());
//			pi.setColumn(id.getColNum());
//			pi.setRow(id.getRowNum());
//			items.add(pi);
//		}
		
		StringBuffer sb = new StringBuffer();
		sb.append("{success:true,user:{userId:'").append(
				currentUser.getUserId()).append("',fullname:'").append(
				currentUser.getFullname()).append("',username:'").append(
				currentUser.getUsername()).append("',depId:'").append(
				curDep.getDepId()).append("',depName:'").append(
				curDep.getDepName()).append("',roleIds:'").append(
						rolestr).append("',rights:'").append(currentUser.getRights().toString().replace("[", "").replace(
				"]", ""));
		
		Gson gson = new Gson();
		sb.append("',topModules:");
		sb.append(gson.toJson(currentUser.getTopModules().values()));
		// sb.append(",items:").append(gson.toJson(items).toString());
		sb.append("},sysConfigs:{");
		//系统配置也在此时加载
		List<SysConfig> sysConfigs = sysConfigService.getAll();
		for(SysConfig sysConfig : sysConfigs){
			sb.append("'")
			  .append(sysConfig.getConfigKey())
			  .append("':'")
			  .append(sysConfig.getDataValue())
			  .append("',");
		}
		if(sysConfigs.size()>0){
			sb.deleteCharAt(sb.length()-1);
		}
		sb.append("}}");
		
		return sb.toString().replaceAll("\"", "'");
	}
	
	/**
	 * 取得组织主要负责人
	 */
	@Transactional(readOnly=true)
	public List<AppUser> getChargeOrgUsers(Department org) {
		
		Set<UserOrg> userOrgs = org.getUserOrgs();
		String isChargeUser = "";
		Iterator<UserOrg> it = userOrgs.iterator();
		while(it.hasNext()){
			UserOrg userOrg = it.next();
			if(userOrg.getIsCharge()!=null&&userOrg.getIsCharge()==1){
				isChargeUser += userOrg.getUserid()+",";
			}
		}
		isChargeUser = isChargeUser.length()==0?"0":isChargeUser.substring(0, isChargeUser.length()-1);
		String hql = "from AppUser au where au.userId in ("+isChargeUser+") and au.delFlag=0";
		return findByHQL(hql);
	}
	
	/**
	 * 按部门取得用户列表
	 */
	@Transactional(readOnly=true)
	public Page<AppUser> getDepUsers(String orgPath, PageRequest pageRequest, Map<String, String> map) {
		if(pageRequest == null){
			pageRequest = new PageRequest(9999999);
		}
		
		if(!"0.".equals(orgPath)) {
			//不显示分管领导
			String hql="select distinct uo.appUser from UserOrg uo " +
				"where uo.isPrimary=1 and uo.organization.path like ? and uo.appUser.delFlag = 0 ";
			if(map!=null){
				if(StringUtils.isNotEmpty(map.get("username").toString())){
					hql += "and uo.appUser.username like '%"+map.get("username").toString().trim()+"%' ";
				}
				if(StringUtils.isNotEmpty(map.get("fullname").toString())){
					hql += "and uo.appUser.fullname like '%"+map.get("fullname").toString().trim()+"%' ";
				}
			}
			//排序
			hql += " order by uo.appUser.orgSn asc, uo.appUser.userSn asc";
			return getEntityDao().findPage(pageRequest, hql, orgPath+"%");
		} else {
			String hql = "from AppUser au where au.delFlag=0 ";
			if(map!=null){
				if(StringUtils.isNotEmpty(map.get("username").toString())){
					hql += "and au.username like '%"+map.get("username").toString().trim()+"%' ";
				}
				if(StringUtils.isNotEmpty(map.get("fullname").toString())){
					hql += "and au.fullname like '%"+map.get("fullname").toString().trim()+"%' ";
				}
			}
			hql += " order by au.orgSn asc, au.userSn asc";
			return getEntityDao().findPage(pageRequest, hql);
		}
	}
	
	/**
	 * 根据roleType进行查询
	 * */
	@Transactional(readOnly=true)
	public Page<AppUser> findByRoleType(PageRequest pageRequest, int roleType) {
		
		Department dept = ContextUtil.getCurrentDept();
		// 显示全部（不包括分管领导）			
		String hql = "from AppUser where department.depId=?";
//		if(roleType == RoleType.ROLE_CHARGE) {
//			// 只显示分管领导
//			hql = "select x.appUser from UserOrg x where x.organization.orgId=? and x.isCharge=1";
//		} else if(roleType == RoleType.ROLE_MASTER) {
//			// 只显示处室负责人
//			hql += " and roleType=2";
//		} else if(roleType == RoleType.ROLE_EMPLOYEE) {
//			hql += " and roleType=3";
//		}
		
		return getEntityDao().findPage(pageRequest, hql, dept.getDepId());
	}

	/**
	 * 用户类型树
	 * */
	public String treeUserRole() {
		RoleType[] types = RoleType.values();		
		StringBuffer sb = new StringBuffer();
		sb.append("[{id:'0', text:'全部', expanded:true, children:[");
		for(RoleType type : types) {
			sb.append("{id:"+type.getValue()+", text:'"+type.getName()+"', leaf:true},");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("]}]");
		
		return sb.toString();
	}

	/**
	 * 根据用户类型查找
	 * */
	public Page<AppUser> findByRole(PageRequest pageRequest, String roleId) {
		String hql = "from AppUser where roleType is not null";
		if(StringUtils.isNotBlank(roleId) && !roleId.equals("0")) {
			hql += " and roleType=" + roleId;
		}
		hql += " order by orgSn asc, userSn asc";
		return getEntityDao().findPage(pageRequest, hql);
	}

}
